package com.palm.core.handler;

import com.jfinal.template.Directive;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.palm.core.ui.tags.ContentTypeTag;
import com.palm.core.ui.tags.DoTag;
import org.noear.solon.Solon;
import org.noear.solon.SolonApp;
import org.noear.solon.core.Aop;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;

import java.util.HashMap;
import java.util.Map;

public class EnjoyHandler implements Handler {
    Engine engine;

    public EnjoyHandler(SolonApp app) {
        engine = Engine.use();
        if (app.cfg().isDebugMode()) {
            engine.setDevMode(true);
        }
        Aop.beanOnloaded(() -> {
            Aop.beanForeach((k, v) -> {
                if (k.startsWith("view:")) {
                    if (Directive.class.isAssignableFrom(v.clz())) {
                        engine.addDirective(k.split(":")[1], (Class<? extends Directive>) v.clz());
                    }
                } else if (k.startsWith("share:")) {
                    engine.addSharedObject(k.split(":")[1], v.raw());
                }
            });
        });
        engine.setBaseTemplatePath("static");
        engine.setToClassPathSourceFactory();
        engine.addDirective("do", DoTag.class);
        engine.addDirective("contentType", ContentTypeTag.class);
    }

    @Override
    public void handle(Context ctx) throws Throwable {
        ctx.setHandled(true);

        try{
            Template template = engine.getTemplate(ctx.path());
            Map<String, Object> params = new HashMap<>();
            params.put("ctx", ctx);
            params.put("cfg", Solon.cfg());
            ctx.contentType("text/html");
            template.render(params, ctx.outputStream());
            ctx.flush();
            ctx.close();
        }catch (IllegalArgumentException e){
            ctx.status(404);
        }

    }
}
